<template>
<div id="editor" class="editor" ref="editor">
  <div style="height:34px;">
    <div class="editor-menu" id="editmenu" ref="menu">
      <button id="bold" title="加粗">
        <svg fill="currentColor" width="24" height="24"><path d="M9 17.025V13h4.418c1.19 0 2.415.562 2.415 2.012s-1.608 2.013-2.9 2.013H9zM9 7h4.336c1 0 1.814.888 1.814 2 0 .89-.814 2-1.814 2H9V7zm8.192 1.899a3.893 3.893 0 0 0-3.888-3.889S9.334 5 8.167 5C7 5 7 6.167 7 6.167v11.666C7 19 8.167 19 8.167 19l5.572.01c2.333 0 4.231-1.86 4.231-4.148a4.122 4.122 0 0 0-1.77-3.372 3.873 3.873 0 0 0 .992-2.591z"></path></svg>
      </button>
      <button id="italic" title="斜体">
        <svg fill="currentColor" width="24" height="24"><path d="M15.751 5h-5.502a.751.751 0 0 0-.749.75c0 .417.336.75.749.75H12l-2 11H8.249a.751.751 0 0 0-.749.75c0 .417.336.75.749.75h5.502a.751.751 0 0 0 .749-.75.748.748 0 0 0-.749-.75H12l2-11h1.751a.751.751 0 0 0 .749-.75.748.748 0 0 0-.749-.75"></path></svg>
      </button>
      <span class="gup"></span>
      <button id="h3" title="标题">
        <svg fill="currentColor" width="24" height="24"><path d="M7 6.007C7 5.45 7.444 5 8 5c.552 0 1 .45 1 1.007v11.986C9 18.55 8.556 19 8 19c-.552 0-1-.45-1-1.007V6.007zm8 0C15 5.45 15.444 5 16 5c.552 0 1 .45 1 1.007v11.986C17 18.55 16.556 19 16 19c-.552 0-1-.45-1-1.007V6.007zM9 11h6v2H9v-2z"></path></svg>
      </button>
      <button id="blockquote" title="引用">
        <svg fill="currentColor" width="24" height="24"><path d="M17.975 12.209c.504.454.822 1.05.952 1.792.061.35.055.715-.022 1.096-.075.379-.209.718-.4 1.018-.465.73-1.155 1.175-2.07 1.337-.874.153-1.684-.06-2.432-.638a3.6 3.6 0 0 1-.916-1.043 3.92 3.92 0 0 1-.506-1.336c-.172-.98-.03-2.026.425-3.142.455-1.116 1.155-2.118 2.1-3.007.8-.757 1.456-1.182 1.97-1.273a.72.72 0 0 1 .544.104.656.656 0 0 1 .286.452c.054.31-.095.601-.45.877-.856.67-1.455 1.27-1.796 1.798-.323.513-.467.873-.43 1.079.034.196.21.287.524.274l.191-.001.249-.029a2.436 2.436 0 0 1 1.781.642zm-7.51 0c.504.454.821 1.05.951 1.792.062.35.056.715-.02 1.096-.077.379-.21.718-.401 1.018-.465.73-1.155 1.175-2.07 1.337-.874.153-1.684-.06-2.432-.638a3.6 3.6 0 0 1-.916-1.043 3.92 3.92 0 0 1-.506-1.336c-.172-.98-.03-2.026.424-3.142.455-1.116 1.156-2.118 2.101-3.007.8-.757 1.456-1.182 1.97-1.273a.72.72 0 0 1 .544.104.656.656 0 0 1 .285.452c.055.31-.094.601-.45.877-.855.67-1.454 1.27-1.796 1.798-.322.513-.466.873-.43 1.079.034.196.21.287.525.274l.191-.001.248-.029a2.436 2.436 0 0 1 1.782.642z"></path></svg>
      </button>
      <button id="pre" title="代码">
        <svg fill="currentColor" width="24" height="24"><path d="M19.718 11.559a.961.961 0 0 1 .007 1.352l-2.201 2.033-1.319 1.219a.937.937 0 0 1-1.33-.005.961.961 0 0 1-.001-1.345l2.813-2.576-2.804-2.568a.96.96 0 0 1-.008-1.352.963.963 0 0 1 1.337 0l2.475 2.289 1.031.953zm-7.462-5.567a1.001 1.001 0 0 1 1.16-.818c.544.096.907.616.81 1.165l-2.082 11.804a1.001 1.001 0 0 1-1.16.818 1.003 1.003 0 0 1-.81-1.165l2.082-11.804zM9.123 8.316a.96.96 0 0 1 0 1.345l-2.812 2.575 2.806 2.569a.962.962 0 0 1 .006 1.35.935.935 0 0 1-1.337 0l-2.093-1.934-1.412-1.305a.961.961 0 0 1-.007-1.352l2.833-2.62.685-.634c.345-.35.976-.354 1.331.006z"></path></svg>
      </button>
      <button id="justifycenter" title="居中">
        <svg fill="currentColor" width="24" height="24"><path d="M4 6 H20 v2 H4 Z M8 11 H16 v2 H8 M4 16 H20 v2 H4 Z"></path></svg>
      </button>
      <span class="gup"></span>
      <button id="inserthorizontalrule" title="分割线">
        <svg fill="currentColor" width="24" height="24"><path d="M4 7c0-.552.445-1 1-1h14c.552 0 1 .444 1 1 0 .552-.445 1-1 1H5c-.552 0-1-.444-1-1zm0 5a1 1 0 0 1 1.01-1h1.98a1 1 0 1 1 0 2H5.01C4.451 13 4 12.556 4 12zm6 0a1 1 0 0 1 1.01-1h1.98a1 1 0 1 1 0 2h-1.98c-.558 0-1.01-.444-1.01-1zm6 0a1 1 0 0 1 1.01-1h1.98a1 1 0 1 1 0 2h-1.98c-.558 0-1.01-.444-1.01-1zM4 17c0-.552.445-1 1-1h14c.552 0 1 .444 1 1 0 .552-.445 1-1 1H5c-.552 0-1-.444-1-1z"></path></svg>
      </button>
      <button id="createlink" title="链接">
        <svg fill="currentColor" width="24" height="24"><path d="M6.77 17.23c-.905-.904-.94-2.333-.08-3.193l3.059-3.06-1.192-1.19-3.059 3.058c-1.489 1.489-1.427 3.954.138 5.519s4.03 1.627 5.519.138l3.059-3.059-1.192-1.192-3.059 3.06c-.86.86-2.289.824-3.193-.08zm3.016-8.673l1.192 1.192 3.059-3.06c.86-.86 2.289-.824 3.193.08.905.905.94 2.334.08 3.194l-3.059 3.06 1.192 1.19 3.059-3.058c1.489-1.489 1.427-3.954-.138-5.519s-4.03-1.627-5.519-.138L9.786 8.557zm-1.023 6.68c.33.33.863.343 1.177.029l5.34-5.34c.314-.314.3-.846-.03-1.176-.33-.33-.862-.344-1.176-.03l-5.34 5.34c-.314.314-.3.846.03 1.177z"></path></svg>
      </button>
      <button id="insertimage" title="图片">
        <svg fill="currentColor" width="24" height="24"><path d="M21 17.444C21 18.3 20.1 19 19 19H5c-1.1 0-2-.7-2-1.556V6.556C3 5.7 3.9 5 5 5h14c1.1 0 2 .7 2 1.556v10.888zm-9.437-3.919a.5.5 0 0 1-.862.013l-1.26-2.065a.5.5 0 0 0-.861.012l-2.153 3.767a.5.5 0 0 0 .435.748h10.292a.5.5 0 0 0 .438-.741L14.573 9.78a.5.5 0 0 0-.872-.006l-2.138 3.75z"></path></svg>
      </button>
      <button id="insertvideo" title="视频">
        <svg fill="currentColor" width="24" height="24"><path d="M21 17.444C21 18.3 20.1 19 19 19H5c-1.1 0 -2 -0.7 -2 -1.556V6.556C3 5.7 3.9 5 5 5h14c1.1 0 2 .7 2 1.556v10.888zm-11 -8.8v7l5-3.55" stroke="#fff">视频</path></svg>
      </button>
      <button class="right dropdown" style="line-height:24px;">
        <svg fill="currentColor" width="24" height="24"><path d="M5 14a2 2 0 1 1 0-4 2 2 0 0 1 0 4zm7 0a2 2 0 1 1 0-4 2 2 0 0 1 0 4zm7 0a2 2 0 1 1 0-4 2 2 0 0 1 0 4z"></path></svg>
        <ul class="dropdown-content">
          <li id="cleareditor">清除</li>
        </ul>
      </button>
    </div>
  </div>
  <span id="tip" class="tip"></span>
  <div class="editor-zone richtext" id="editzone" ref="editzone" contenteditable="true"></div>
  <!-- 插入链接时展示 -->
  <div id="modal" ref="modal" v-show="isShow">
  	<div class="panel center index">
  	  <div id="close" ref="close">
  	  	<svg fill="currentColor" width="24" height="24"><path d="M13.486 12l5.208-5.207a1.048 1.048 0 0 0-.006-1.483 1.046 1.046 0 0 0-1.482-.005L12 10.514 6.793 5.305a1.048 1.048 0 0 0-1.483.005 1.046 1.046 0 0 0-.005 1.483L10.514 12l-5.208 5.207a1.048 1.048 0 0 0 .006 1.483 1.046 1.046 0 0 0 1.482.005L12 13.486l5.207 5.208a1.048 1.048 0 0 0 1.483-.006 1.046 1.046 0 0 0 .005-1.482L13.486 12z"></path></svg>
  	  </div>
  	  <div class="panel-title">
  	  	<h3>插入链接</h3>
  	  </div>
  	  <div class="panel-body">
  	  	<input type="text" v-model="link" spellcheck="false" autofocus="autofocus" placeholder="输入链接">
  	  	<span class="col-4 right"><button type="button" ref="sure" class="btn blue">确认</button></span>
  	  </div>
  	</div>
  </div>
  <!-- 插入图片时展示 -->
	<div id="modal" ref="modal" v-show="isUpload">
		<div class="panel center index">
			<div id="close" ref="close">
				<svg fill="currentColor" width="24" height="24"><path d="M13.486 12l5.208-5.207a1.048 1.048 0 0 0-.006-1.483 1.046 1.046 0 0 0-1.482-.005L12 10.514 6.793 5.305a1.048 1.048 0 0 0-1.483.005 1.046 1.046 0 0 0-.005 1.483L10.514 12l-5.208 5.207a1.048 1.048 0 0 0 .006 1.483 1.046 1.046 0 0 0 1.482.005L12 13.486l5.207 5.208a1.048 1.048 0 0 0 1.483-.006 1.046 1.046 0 0 0 .005-1.482L13.486 12z"></path></svg>
			</div>
			<div class="panel-title">
				<h3>上传图片</h3>
			</div>
			<div class="panel-body">
					<v-upload @preview="preview" :type="mt" ref="removeFiles"></v-upload>
			</div>
		</div>
	</div>
</div>
</template>

<script>
import vUpload from '@/components/Upload';
import app from '@/utils';
import { getdom } from '@/aui/common'

export default {
  name: 'editor',
  props: ['content'],
  data() {
  	return {
      link: '',
      banner: [],
      isShow: false,
      isUpload: false,
      mt: '',
      offsetTop: 40,
      timer: null,
      cont: ''
  	}
  },
  created() {
    this.cont = this.content;
  },
  mounted() {

    this.editor();
    this.init();
    this.timer = setInterval(() => {
      this.autoCache();
    }, 30000)
  },
  components: {
    vUpload
  },
  methods: {
  	linkCom: function(com) {
      this.isShow = true;
  	  let selection = document.getSelection();
  	  let range = selection.getRangeAt(0);
  	  let sure = this.$refs.sure,
  	  	  cancel = this.$refs.cancel,
  	  	  close = this.$refs.close;
  	  close.onclick = () => {
        this.isShow = false;
        this.link = '';
  	  }
  	  sure.onclick = () => {
  	  	if(com == 'createlink') {
  	  	  let tpl = `<a href="${this.link}"></a>`;
  	  	  let dom = app.parseDom(tpl)[0];
  	  	  range.surroundContents(dom);
  	  	}
        this.link = '';
  	  	this.isShow = false;
  	  }
    },
    insertImg(com) {
      this.isUpload = true;
      this.mt = 'image';
      let close = this.$refs.close;
      close.onclick = () => {
        this.isUpload = false;
        this.$refs.removeFiles.removeFiles();
      };
    },
    insertVideo(com) {
      this.isUpload = true;
      this.mt = 'video'
      const close = this.$refs.close;
      close.onclick = () => {
        this.isUpload = false;
        this.$refs.removeFiles.removeFiles();
      }
    },
    selection: function(com) {
  	  let selection = document.getSelection();
  	  let text = selection.toString();
  	  let range = selection.getRangeAt(0);
  	  let span = document.createElement('span');
  	  span.style = "display:block;margin:5px;";
  	  if(com == 'pre') {
  	  let pre = document.createElement('pre');
  	  pre.style = "margin:10px 0;padding:5px;overflow:auto;\
  	  			  background-color:#f6f8fa;border-radius:4px;font-family:Menlo,Monaco,Consolas,Andale Mono;";
  	  range.surroundContents(span);
  	  range.surroundContents(pre);
  	  }else if(com == 'blockquote') {
  	  	let blockquote = document.createElement('blockquote');
  	  	blockquote.style = "margin:10px 0;padding:5px 10px;background-color:#f6f8fa;border-left:3px solid #ddd;";
  	  	range.surroundContents(span);
  	  	range.surroundContents(blockquote);
  	  }
  	},
  	insert: function() {
  	  let editzone = document.getElementById('editzone');
  	  let tpl = `<div class="richtext"><br/></div>`;
  	  let dom = app.parseDom(tpl);
  	  editzone.append(dom[0]);
  	},
  	// 根据菜单格式化文本
  	editor: function() {
      let editmenu = this.$refs.menu.children;
      let _this = this;
      for(let i=0; i<editmenu.length; i++) {
        editmenu[i].onclick = function() {
          let com = this.getAttribute('id');
          if(com == 'createlink') {
          	_this.linkCom(com, _this.link);
          }else if(com == 'insertimage') {
          	_this.insertImg(com);
          }else if(com == 'insertvideo') {
            _this.insertVideo(com);
          }else if(com == 'blockquote') {
          	_this.selection(com);
          	_this.insert();
          }else if(com == 'pre') {
          	_this.selection(com)
          	_this.insert()
          }else if(com == 'inserthorizontalrule') {
          	document.execCommand(com, false);
          	_this.insert();
          }else if(com == 'h3') {
          	document.execCommand('formatblock', false, '<h3>');
          }else if(com == 'cleareditor') {
            _this.$refs['editzone'].innerHTML = '<p><br/></p>';
            app.rmStorage('editor_content');
          }else {
            document.execCommand(com, false);
          }
        }
      }
      window.addEventListener('scroll', () => {
        // 滚动条距视窗顶端距离
        let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        // 编辑器距顶端的偏移距离
        let editorTop = this.$refs['editor'] && this.$refs['editor'].offsetTop;
        if(!this.$refs['menu']) return;
        if(scrollTop >= editorTop - this.offsetTop) {
          this.$refs['menu'].style = "position:fixed;top:46px;width:81.2%;z-index:111;background-color:#f3f7f8;"
        }else {
          this.$refs['menu'].style = "";
        }
      })
    },
    // 获取上传图片
    preview(data) {
      this.url = data.url;
      let domStr = ``,
          image = new Image();
      if(data.type == 'image') {
        domStr = `<p class="image" contenteditable="false" style="position:relative;width:50%;margin:5px auto;">
                    <img src="${data.url}" style="width: 100%;height:auto;vertical-align:middle;">
                  </p>`;
      }else if(data.type = 'video') {
        domStr = `<p class="video" contenteditable="false" style="position:relative;width:50%;margin:5px auto;">
                    <video controls style="width: 100%;height:auto;vertical-align:middle;">
                      <source src="${data.url}" />
                    </video>
                  </p>`
      }
      const selection = document.getSelection(),
            frag = app.parseDom(domStr);
      if(!selection.anchorNode) {
        this.$refs.editzone.append(frag[0]);
        this.$refs.editzone.append(app.parseDom('<p><br/></p>')[0]);
      }else {
        let range = selection.getRangeAt(0);
        range.endContainer.append(frag[0]);
        range.endContainer.append(app.parseDom('<p><br/></p>')[0]);
        selection.removeRange(range);
      }
      this.setImg();  // 存在预览图片后开启此方法
      this.isUpload = false;
      this.$refs.removeFiles.removeFiles();
    },
    setImg() {
      const imgArr = document.querySelectorAll(`.image`),
          tpl = `<div id="setting" contenteditable="false">
                  <button id="setbanner">设为封面</button>
                  <select id="setsize">
                    <option value="50%">50%</option>
                    <option value="100%">100%</option>
                  </select>
                </div>`,
          dom = app.parseDom(tpl)[0];
      let banner = '';
      for(let i=0,len=imgArr.length; i<len; i++) {
        imgArr[i].onmouseenter = e => {
          const img = e.target.children[0].src;
          e.target.classList.add('img');
          e.target.append(dom);
          const setBanner = document.querySelector('#setbanner');
          setBanner.onclick = e => {
            banner = img;
            this.$emit('transmit', banner);
            app.flash('success', '设置成功！');
          }
        }
        imgArr[i].onmouseleave = e => {
          e.target.classList.remove('img');
          e.target.removeChild(dom);
        }
      }
    },
    // 自动缓存 5s
    autoCache() {
      const strDom = getdom('#editzone').innerHTML;
      app.setStorage('editor_content', strDom);
      getdom('#tip').innerText = '已保存';
      console.log('290...', new Date().getSeconds());
      let timer = null;
      timer = setTimeout(() => {
        getdom('#tip').innerText = '';
        clearTimeout(timer);
        timer = null;
      }, 2000);
    },
    // init editor
    init() {
      if(this.cont) return this.$refs['editzone'].innerHTML = this.cont;
      const strDom = app.getStorage('editor_content');
      if(strDom) {
        this.$refs['editzone'].innerHTML = strDom.data;
      }else {
        this.$refs['editzone'].innerHTML = '<p><br/></p>';
      }
    }
  },
  unmounted() {
    console.log('310...........');
    clearInterval(this.timer);
    this.timer = null;
  }
}
</script>

<style lang="less">
@keyframes right_out {
  from {
    left: -30px;
    opacity: 0;
  }
  to {
    left: 0;
    opacity: 1;
  }
}
@keyframes bottom_out {
  from {
    height: 0;
    opacity: 0;
  }
  to {
    height: auto;
    opacity: 1;
  }
}
/**
 * Editor by vikeel
 */
.editor {
  position: relative;
  width: 100%;
  border-top: 1px solid #eee;
  .tip {
    animation: bottom_out 1s ease;
    position: absolute;
    right: 0;
    top: 36px;
    font-size: 12px;
    color: #888;
  }
}
.editor-menu {
  width: 100%;
  border-bottom: 1px solid #eee;
  background-color: #fff;
  .gup {
    display: inline-block;
    width: 1px;
    height: 20px;
    margin: 0 3px;
    vertical-align: middle;
    background-color: #ebebeb;
  }
  button {
    border: 0;
    outline: 0;
    padding: 4px;
    line-height: 1px;
    vertical-align: middle;
    color: #8590a6;
    background-color: inherit;
    cursor: pointer;
    &:hover {
      background-color: #f6f8fa;
    }
  }
  .dropdown {
    position: relative;
    // width: 60px;
    height: 32px;
    .dropdown-content {
      display: none;
      position: absolute;
      left: 0;
      width: 100%;
      animation: bottom_out 1s ease;
      background-color: #f6f8fa;
      li {
        font-size: 12px;
      }
    }
    
  }
  .dropdown:hover .dropdown-content {
    display: block;
  }
}
#link-input::-webkit-input-placeholder {
  font-size: inherit;
}
.editor-zone {
  min-height: 380px;
  padding: 30px 15px 35px;
  border-bottom: 1px solid #ddd;
  outline: 0;
  background-color: #fff;
  overflow: hidden;
}
.richtext {
  div {
    // position: relative;
    width: 100%;
  }
  hr {
    width: 238px;
    max-width: 100%;
    margin: 15px auto 30px;
    border: 0;
    border-top: 1px solid #ddd;
  }
  h3 {
    font-size: 1.3rem;
    font-weight: 500;
  }
  p {
    margin: 5px 0;
  }
  a {
    color: #007fff;
  }
  
}
/** img setting */
.richtext .img {
  position: relative;
}
.richtext .img::after {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0,0,0,.3);
}
.video {
  video {
    width: 100%;
    height: auto;
  }
}
/**
 * Link panel
 */
.panel-body:after {
  content: '';
  display: table;
  clear: both;
}
#modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(225,225,225,.5);
}
#modal .panel {
  position: relative;
  margin-top: 20%;
}
#modal .panel input {
  width: 100%;
}
#close {
  position: absolute;
  top: 8px;
  right: 10px;
  padding: 3px;
  line-height: 1px;
  cursor: pointer;
}
#close:hover {
  background-color: #eee;
}

/** tools */
#setting {
  animation: right_out 1s ease;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 110;
  button,
  select {
    display: block;
    width: 60px;
    height: 24px;
    border: 0;
    border-radius: 0 2px 2px 0;
    margin: 5px 0;
    background-color: rgba(225,225,225,.9);
    font-size: 12px;
    line-height: 24px;
    text-align: center;
    cursor: pointer;
  }
  // button:hover {
  //   background-color: #fff;
  // }
}
</style>